package com.kelly.kellymusicplayer.activity;

import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.Toast;

import com.kelly.kellymusicplayer.R;
import com.kelly.kellymusicplayer.Utils.MusicHelper;
import com.kelly.kellymusicplayer.adapter.MusicListAdapter;
import com.kelly.kellymusicplayer.entity.MusicInfo;
import com.kelly.kellymusicplayer.listener.OnPlayerStartListener;
import com.kelly.kellymusicplayer.listener.OnProgressListener;
import com.kelly.kellymusicplayer.tools.MusicPlayManager;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends Activity implements View.OnClickListener {

    private MusicPlayManager musicPlayManager;
    private MusicListAdapter musicListAdapter;

    private ListView lv_misicList;
    private SeekBar sb_progress;
    private ImageView iv_previous;
    private ImageView iv_playOrPause;
    private ImageView iv_next;

    private OnPlayerStartListener onPlayerStartListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        musicPlayManager = MusicPlayManager.getInstance(this);
        setContentView(R.layout.activity_main);
        initView();
        initEvent();
        initMusicData();
    }

    private void initEvent() {
        musicPlayManager.setProgressListener(new OnProgressListener() {
            @Override
            public void getProgress(int currentPermill) {
                if (is_refresh_progrss)
                    sb_progress.setProgress(currentPermill);
            }
        });
        onPlayerStartListener = new OnPlayerStartListener() {
            @Override
            public void onPlayerStart() {
                iv_playOrPause.setImageResource(R.drawable.icon_pause);
            }
        };
        musicPlayManager.setOnPlayerStartListener(onPlayerStartListener);
    }

    private void initMusicData() {
        List<MusicInfo> musicInfoList = MusicHelper.getMusicInfo(getContentResolver());
        musicListAdapter = new MusicListAdapter(this, musicInfoList);
        musicPlayManager.setMusicInfoList(musicInfoList);
        lv_misicList.setAdapter(musicListAdapter);
        lv_misicList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                musicPlayManager.playMusicList(i);
            }
        });
    }

    private boolean is_refresh_progrss = false;

    private void initView() {
        lv_misicList = (ListView) findViewById(R.id.lv_misicList);
        sb_progress = (SeekBar) findViewById(R.id.sb_progress);
        sb_progress.setMax(1000);
        sb_progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser)
                    musicPlayManager.seekTo(musicPlayManager.getDuration() * progress / 1000);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                is_refresh_progrss = false;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                is_refresh_progrss = true;
            }
        });
        iv_previous = (ImageView) findViewById(R.id.iv_previous);
        iv_playOrPause = (ImageView) findViewById(R.id.iv_playOrPause);
        iv_next = (ImageView) findViewById(R.id.iv_next);

        iv_previous.setOnClickListener(this);
        iv_playOrPause.setOnClickListener(this);
        iv_next.setOnClickListener(this);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        musicPlayManager.stop();
    }

    /**
     * 菜单、返回键响应
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click(); //调用双击退出函数
        }
        return false;
    }

    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            finish();
            System.exit(0);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_previous:
                musicPlayManager.playPreviousMusic();
                break;
            case R.id.iv_playOrPause:
                if (musicPlayManager.isPlaying()) {
                    musicPlayManager.pause();
                    iv_playOrPause.setImageResource(R.drawable.icon_start);
                } else {
                    musicPlayManager.resume();
                    iv_playOrPause.setImageResource(R.drawable.icon_pause);
                }
                break;
            case R.id.iv_next:
                musicPlayManager.playNextMusic();
                break;
        }
    }

    /**
     * 监听电话
     */
    public class CallReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // 如果是去电
            if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
            } else {
                TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
                tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
            }
        }

        PhoneStateListener listener = new PhoneStateListener() {
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                super.onCallStateChanged(state, incomingNumber);
                switch (state) {
                    case TelephonyManager.CALL_STATE_IDLE://挂断
                        break;
                    case TelephonyManager.CALL_STATE_OFFHOOK://接听
                        if (musicPlayManager.isPlaying()) {
                            musicPlayManager.pause();
                            iv_playOrPause.setImageResource(R.drawable.icon_start);
                        }
                        break;
                    case TelephonyManager.CALL_STATE_RINGING://响铃
                        if (musicPlayManager.isPlaying()) {
                            musicPlayManager.pause();
                            iv_playOrPause.setImageResource(R.drawable.icon_start);
                        }
                        break;
                }
            }
        };
    }
}
